<template>
    <div class="contract-list-page change-bank-card-list">
        <rui-page :defines="defines">
            <!-- <Row>
                <Col span="24">
                    <Button type="primary" class="export-btn" @click="showModal">新增申请</Button>
                </Col>
            </Row>-->
            <rui-query ref="formDom" :label-width="120" :query="queryData" :query-rows="formOptions"></rui-query>

            <rui-table
                ref="tableDom"
                defineId="defineData"
                ref-query="formDom"
                @loadDatas="queryData"
                :columns="tableColumns"
                :showIndex="false"
                :slots="[{key:'action',slot:'action'},{key:'applyNo',slot:'applyNo'},{key:'businessSource',slot:'businessSource'}]"
                @on-selection-change="onSelectionChange"
            >
                <template slot="toolBar">
                    <Button @click="showModal" icon="md-add" type="primary">新增申请</Button>
                    <!-- <Button @click="" type="primary">导出报表</Button> -->
                    <Button type="primary" class="export-btn" :disabled="resolveDisable"
                            @click="resolve('suggestCheckF')">签约
                    </Button>
                    <Button type="primary" class="export-btn" :disabled="resolveDisable"
                            @click="resolve('suggestRejectF')">拒绝
                    </Button>
                    <Button type="primary" class="export-btn" :disabled="submissionable"
                            @click="resolve('suggestCheckF')">报送
                    </Button>
                    <Button type="primary" class="export-btn" :disabled="modelable" @click="dowmloadAnnex('DROP')">
                        下载删除清单
                    </Button>
                    <Button type="primary" class="export-btn" :disabled="modelable" @click="dowmloadAnnex('INCREASE')">
                        下载新增清单
                    </Button>
                    <Button type="primary" class="export-btn" :disabled="modelable" @click="downloadExcel('DETAIL')">
                        下载业务清单
                    </Button>
                    <Button type="primary" class="export-btn" :disabled="modelable" @click="dowmloadAnnex('PERMIT')">
                        下载授权书影像清单
                    </Button>
                </template>
                <template slot="action" slot-scope="{ row }">
                    <Button :disabled="!row.isViewBtn" type="primary" size="small" @click="showContractDetial(row)">处理
                    </Button>

                    <Button :disabled="row.processStatus !== 'draft'" type="primary" size="small"
                            @click="showContractDetial(row)">编辑
                    </Button>

                    <Button :disabled="row.processStatus !== 'draft'" type="error" size="small" @click="del(row)">删除
                    </Button>
                </template>
                <template slot-scope="{ row, index }" slot="applyNo">
                    <a class="applyNo" @click="showContractDetial(row,true)">{{row.applyNo}}</a>
                </template>
                <template slot-scope="{ key,item,data,dataDic }" slot="businessSource">
                    <span>{{getTitle(dataDic,businessSource)}}</span>
                </template>
            </rui-table>
        </rui-page>
        <Table :columns="[]" :data="[]" ref="table" style="display: none;"></Table>
        <!-- <button @click="showContractDetial">银行卡变更详情</button> -->
        <ActivatedCase
            :isSP="isSP"
            :getDataFn="getDataFn"
            :contractBusiness="contractBusiness"
            :dataDict="dataDict"
            :modal="modal"
            modalTitle="已激活案件列表"
            @showContractDetial="showContractDetial"
            @closeModal="closeModal"
        />
        <Spin size="large" fix v-if="spinShow"></Spin>
    </div>
</template>

<script>
    import {mapGetters} from "vuex";

    import defineData from "./defineData";
    import {
        delBankCardChange,
        downloadBatchFile,
        downloadExcel,
        findActivatedContractList,
        getComAttach,
        getManageBankCardChangeList,
        passOrReject
    } from "_p/basic/api/contract/post-loan-info-change";
    import {businessSource, channelType} from "_p/basic/api/contract/channel-type/channel-type";
    import {getDictDataList} from "_p/basic/assets/contract/js/utils";

    import ActivatedCase from "_p/basic/pages/contract/common/activated-case/index";

    export default {
        //
        name: "ChangeBankCardList",
        components: {
            ActivatedCase,
        },
        data() {
            return {
                templateModel: false,
                attachmentList:"",
                selection: [],
                modelable: true,
                submissionable: true,
                resolveDisable: true,

                contractBusiness: [
                    "advanceSettle",
                    "closeContract",
                    "bankCardChange"],
                pageNo: 1,
                openModal: false,
                defines: [],
                loading: false,
                isSP: null,
                spinShow: false,
                // 处理状态(processStatus) 来源(dataSource) 变更主体(PersonRoleType) 合同状态/合同申请状态(contractStatus) 渠道类型(channelType)
                // 已激活案件列表: contractStatus 合同状态 channelType 渠道类型
                dicttArr: [
                    "bankProcessStu",
                    "dataSource",
                    "PersonRoleType",
                    "contractStatus",
                    "channelType",
                ],
                modal: false,
                dataDict: {},
                formOptions: [
                    {
                        defineId: "defineData",
                        span: 8,
                        fields: [
                            "contractNo",
                            "applyNo",
                            "custName",
                            "dataSource",
                            "oldBank",
                            "newBank",
                            "processStatus",
                            "createTimeForm",
                            "endDateForm",
                            "dispatchTimesForm",
                        ],
                    },
                    // {
                    //     defineId: "defineData",
                    //     span: 8,
                    //     fields: ["contractNo", "custName", "processStatus"]
                    // },
                    // {
                    //     defineId: "defineData",
                    //     span: 8,
                    //     fields: ["applyNo", "createTime", "endDate"]
                    // }
                ],
                // formOptionsMore: [
                //     {
                //         defineId: "defineData",
                //         span: 8,
                //         fields: ["dispatchTimes"]
                //     }
                // ],
                tableColumns: [
                    "action",
                    "applyNo",
                    "contractNo",
                    "custName",
                    "contactNo",
                    "processStatus",
                    "oldBank",
                    "newBank",
                    "dataSource",
                    "dispatchTimes",
                    "endDate",
                    "startDate",
                    "createTime",
                    "createBy",
                    "businessSource",
                    "selection",
                ],
            };
        },
        computed: {
            ...mapGetters({
                userInfo: "userInfo",
                roleType: "roles",
            }),
            getDataFn: () => findActivatedContractList,
        },

        created() {
            this.defines.push({ id: "defineData", fields: defineData });
            this.isSP = channelType(this.$route.meta.params);
            // businessSource 通过 roleType 获取 值: BUSINESS_PEOPLE / SP
            this.businessSource = businessSource(this.roleType);
        },
        mounted() {
            console.group("银行卡变更","页面初始数据：");
            console.log("userInfo:", this.userInfo);
            console.log("roleType:", this.roleType);
            console.log("businessSource:", this.businessSource);
            console.log("isSP:", this.isSP);
            console.log("contractNo:", this.contractNo);
            console.groupEnd();
        },
        activated() {
            this.init();
        },
        methods: {
            init() {
                this.getDictDataList();
            },
            getDictDataList() {
                getDictDataList(this.dicttArr).then((res) => {
                    console.group("数据字典:");
                    console.log(this.dicttArr.join("  "));
                    console.log(JSON.parse(JSON.stringify(res)));
                    console.groupEnd();
                    this.dataDict = res;
                });
                // 在数据字典返回后调请求
                // this.queryData(this.$refs.formDom.getFormData());
                this.$refs['tableDom'].reloadData();
            },
            queryData(queryData) {
                if (this.loading || !queryData) return;
                const { condition } = queryData;
                let data,
                    startCreateDate = "",
                    endCreateDate = "",
                    startFinishDate = "",
                    endFinishDate = "",
                    startDispatchTimes = "",
                    endDispatchTimes = "";

                this.loading = true;

                if (condition) {
                    if (Array.isArray(condition.createTimeForm)) {
                        startCreateDate = condition.createTimeForm[0];
                        endCreateDate = condition.createTimeForm[1];
                    }
                    if (Array.isArray(condition.endDateForm)) {
                        startFinishDate = condition.endDateForm[0];
                        endFinishDate = condition.endDateForm[1];
                    }
                    if (Array.isArray(condition.dispatchTimesForm)) {
                        startDispatchTimes = condition.dispatchTimesForm[0];
                        endDispatchTimes = condition.dispatchTimesForm[1];
                    }
                }

                data = Object.assign({}, condition, {
                    pageNumber: queryData.pageNumber,
                    pageSize: queryData.pageSize,
                    // 申请时间起
                    startCreateDate,
                    // 申请时间止
                    endCreateDate,
                    // 完成时间起
                    startFinishDate,
                    // 完成时间止
                    endFinishDate,
                    //派单时间起
                    startDispatchTimes,
                    //派单时间止
                    endDispatchTimes,
                });

                getManageBankCardChangeList(data)
                    .then((res) => {
                        console.log(res, "getManageBankCardChangeList");
                        if (res.code === "0000" && res.data) {
                            let { records, total } = res.data;
                            // 控制表格前面复选框选中，审核和完成状态也允许选择复选框
                            Array.isArray(records) && records.forEach(e => {
                                e._disabled = !e.isViewBtn
                                if(e.processStatus == 'approved'){
                                    e.isViewBtn = false;
                                    e._disabled =false;
                                }
                                if(e.processStatus == 'underReview'){
                                    e._disabled =false;
                                }
                            })
                            this.$refs.tableDom.updateTableData(records, total);
                        }
                        this.loading = false;
                    })
                    .catch((e) => {
                        console.error(e);
                        this.loading = false;
                    });
            },
            // 删除
            del(row) {
                if (!row.contractNo) return;
                this.$Modal.confirm({
                    title: "确认删除？",
                    onOk: () => {
                        this.deleteQuery(row.caseNo);
                    }
                });
            },
            deleteQuery(caseNo) {
                delBankCardChange(caseNo).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        // this.contractTable = res.data;
                        this.$Message.success(res.data);
                        this.$emit("getList", this.formValidate);
                        this.init();
                    }
                });
            },

            showContractDetial(params, isReadOnly) {
                if (!params && !params.contractNo) return;
                if (isReadOnly) params.isReadOnly = true;
                this.afs.newTab(
                    this,
                    "projects/basic/pages/contract/post-loan-info-change/change-bank-card-detial/index",
                    "银行卡变更详情",
                    "ios-add",
                    params,
                    "change-bank-card-detial-" + this.pageNo,
                    [],
                    true
                );
                this.pageNo += 1;
            },
            getTitle(data, val) {
                if (!val || !Array.isArray(data)) return '';
                let d = data.filter(i => i.value == val);
                if (d[0] && d[0].title) {
                    return d[0].title;
                }
                return val; // 没有数据返回原值
            },

            onSelectionChange(selection) {
                console.log(selection, 'selection');
                //报送中的才会允许签约/拒绝 出现按钮
                if (selection && selection.length > 0) {
                    var status = selection[0].processStatus;
                    selection.forEach((item) => {
                        this.resolveDisable = false;
                        if (item.processStatus == 'underReview') {
                            this.resolveDisable = true;//拒绝
                            this.submissionable = true;//报送
                            this.modelable = false;//下载影像件
                        } else if (item.processStatus == 'noSubmission') {
                            this.resolveDisable = true;
                            this.submissionable = false;
                            this.modelable = false;
                        } else if (item.processStatus == 'approved') {
                            this.resolveDisable = true;
                            this.submissionable = true;
                            this.modelable = false;
                        } else if (item.processStatus == 'submission') {
                            this.resolveDisable = false;
                            this.submissionable = true;
                            this.modelable = false;
                        }
                    })
                } else {
                    this.resolveDisable = true;
                    this.submissionable = true;
                    this.modelable = true;
                }
                this.selection = selection
            },
            // 提交（suggestCheckF），拒绝（suggestRejectF）
            resolve(name) {
                this.$Modal.confirm({
                    title: `确认提交？`,
                    onOk: () => {
                        this.spinShow = true
                        this.passOrReject(name)
                    }
                });
            },
            dowmloadAnnex(type){
                this.spinShow = true
                this.dowmloadTemplate(type)
            },
            // 一键提交 请求
            passOrReject(type) {
                let d = { approvalOperating: type, bankCardManageVOs: this.selection }
                passOrReject(d).then(res => {
                    this.spinShow = false
                    if (res.code === "0000") {
                        this.$Message.success("成功");
                        this.init();
                    }
                }).catch(e => {
                    console.error(e);
                    this.spinShow = false
                })
            },
            //一键下载附件
            dowmloadTemplate(modelType) {
                let d = {typeEnum: modelType, bankCardManageVOs: this.selection}
                console.log("下载附件参数", d)
                //获取模板列表
                if (!d) return;
                getComAttach(d).then(res => {
                    //关闭下载完成后的加载状态
                    this.spinShow = false
                    if (res.code === '0000') {
                        this.attachmentList = res.data;
                        console.log(res, "下载前")
                        this.downBatchFile(res.data);
                    }
                }).catch(e => {
                    console.error(e);
                    this.spinShow = false
                })
            },
            downBatchFile(v) {
                console.log("downBatchFile获取的参数为", v)
                let params = {
                    attachmentList: v.bankCardManageVOs,
                }
                console.log(params, "调用的参数集合")
                let self = this
                downloadBatchFile(v).then(function (response) {
                    if (response.status === 200) {
                        self.afs.downloadFile(response);
                        this.$Message.success("下载完成")
                    }
                })
            },
            downloadExcel(){
                let arr = [],newBank;
                if(Array.isArray(this.selection)){
                    for (let i=0;i<this.selection.length;i++){
                        if(newBank && newBank !== this.selection[i].newBank) {
                            this.$Message.error("所选择业务清单不一致，请重新选择！")
                            return ;
                        } else {
                            newBank = this.selection[i].newBank
                        }
                        arr.push(this.selection[i].caseNo)
                    }
                }
                this.spinShow = true;
                downloadExcel(arr).then(res => {
                    this.spinShow = false;
                    if(res.code === "0000" && res.data){
                        let data = [];
                        Array.isArray(res.data) &&  res.data.forEach(e => {
                            console.log("excel数据",e)
                            e.newBankAccount =  e.newBankAccount ? "\t" + e.newBankAccount : null;
                            e.oldBankAccount =  e.oldBankAccount ? "\t" + e.oldBankAccount : null;
                            e.certNo =  e.certNo ? "\t" + e.certNo : null;
                            e.endDate =  e.endDate ? "\t" + e.endDate : null;
                            e.custName =  e.custName ? "\t" + e.custName : null;
                            data.push(e)
                        })
                        this.bankExcelHead(newBank,data)
                    }
                }).catch(e => {
                    this.spinShow = false;
                    console.error(e)
                })
            },
            bankExcelHead(bankId, data) {
                let columns = [
                    {key: 'applyNo', title: "申请号"},
                    {key: 'newCardholder', title: "姓名"},
                    {key: 'newBankAccount', title: "新增账号"},
                    {key: 'oldBankAccount', title: "删除账号"},
                    {key: 'certNo', title: "身份证号"},
                    // {key: 'endDate', title: "有效期"},
                ];
                switch (bankId) {
                    case '101': //中国银行
                        columns = [{key: 'newCardholder', title: "个人名称"}, {key: 'newBankAccount', title: "个人账号"}, {key: 2, title: "中行代扣业务清单"},]
                        break;
                    case '137': // 中国工商银行
                        columns.push({key: 'closeTime', title: "授权书有效期"})
                        break;
                    case '5500814':    // 中国邮政储蓄银行
                        break;
                    case '524853':    // 中国建设银行
                        break;
                }
                this.$refs.table.exportCsv({
                    filename: '业务清单',
                    columns,
                    data
                });
            },
            // 弹窗
            showModal() {
                this.modal = true;
            },
            closeModal() {
                this.modal = false;
            },

        },
    };
</script>
<style lang="less">
    @import "../../../../styles/common/form.less";
</style>
